package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *
 * 聚通达
 *二、个性短信
 */
    public class SmsApiJTDv2 extends GateWayHttpAbstract
{

    public SmsApiJTDv2(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        HashMap<String,String> header = Maps.newHashMap();
        header.put("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        Map<String,Object> params = Maps.newHashMap();
        params.put("uid",paramsMaps.get("uid"));
        params.put("password", DigestUtils.md5Hex(paramsMaps.get("password")).toUpperCase());
        params.put("mobile",mt.getPhone());
        params.put("encode","utf-8");
        String content = "";
        for (int i = 0; i < mt.getPhone().split(",").length ; i++) {
            try{
                content  += Base64.encodeBase64String(mt.getSmsContent().getBytes()) + ",";
            }catch (Exception e){
                e.printStackTrace();
                logger.error("网关:{},手机：{},内容：{}，内容编码错误。", this.gateWayID, mt.getPhone(), mt.getSmsContent());
            }
        }
        params.put("content",content.substring(0,content.length()-1));
        params.put("extNumber",paramsMaps.get("extNumber")); //扩展码
        params.put("encodeType", "base64");
        String result =  HttpRequest.sendFormPost(paramsMaps.get("apiUrl") + "/jtdsms/sendData.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null, "utf-8", 2000);
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        List<SMSSRMessage> resultList = Lists.newArrayList();
        String data = "qx" + result;
        int phoneNum = mt.getPhone().split(",").length;
        for (int i = 0; i < phoneNum; i++) {
            SMSSRMessage message = initGatewayResultMessage(data, mt, "qx");
            String resultCode = null;
            String resultMessage = null;
            String taskid = null;
            if(StringUtils.equals(message.getResult(), "F10199")) {
                resultMessage = "success";
                resultCode = "0";
                if (result.length() > 10) {
                    taskid = result;
                } else {
                    resultCode = result;
                    resultMessage = result;
                }
                message.setMsgkey(mt.getPhone());
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
                resultList.add(message);
            }
        }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            logger.info("通道：{}，异步推送状态结果：{}",this.gateWayID, text);
            try {
                text = URLDecoder.decode(text,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.error("推送报告通道：{}，url解析错误，结果：{}",this.gateWayID, text);
            }
            String[] lines = text.substring(4).split(";");
            for (int i = 0; i < lines.length; i++) {
                String[] data = lines[i].split(",");
                SMSRTMessage smsRtMessage = initSmsRtMessage(data[4], data[3], data[3], data[5], "DELIVRD");
                rtList.add(smsRtMessage);
            }
        }
        return new SmsHttpMsgResponse("0");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        Map<String,String> map = Maps.newHashMap();
        if (StringUtils.isNotBlank(text)) {
            logger.info("通道：{}，异步推送上行结果：{}",this.gateWayID, text);
            try {
                text = URLDecoder.decode(text.substring(4),"utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("通道：{}，推送上行url解析错误，结果：{}",this.gateWayID, text);
                e.printStackTrace();
            }
            String[] data = text.split(",");
            SMSMOMessage sMSMOMessage = new SMSMOMessage();
            sMSMOMessage.setGateWayID(gateWayID);
            String conetent = data[4];
            sMSMOMessage.setMsgContent(conetent);
//                sMSMOMessage.setMsgid(data.getString("moid"));
            sMSMOMessage.setPhone(data[3]);
            sMSMOMessage.setSenttime(data[5]);
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
            sMSMOMessage.setUuid(UUID.randomUUID().toString());
            moList.add(sMSMOMessage);
        }
        return new SmsHttpMsgResponse("0");
    }

    @Override
    public String queryReport(String jsonText) {
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("uid",paramsMaps.get("uid"));
        String auth = DigestUtils.md5Hex(paramsMaps.get("password")).toUpperCase();
        params.put("password", auth);
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/jtdsms/balance.do", Joiner.on("&").withKeyValueSeparator("=").join(params),null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        if (Integer.parseInt(result) > 0) {
            return "余额：" + result;
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)throws Exception
    {
        String params = "{\"uid\":\"202723\",\"password\":\"226553\",\"apiUrl\":\"http://119.90.36.56:8090\",\"extNumber\":\"\"}";
        SmsApiJTDv2 api = new SmsApiJTDv2("ZY",params);
//        String balance = api.balance();
        String sign = DigestUtils.md5Hex("hyxx#7#m2@6");
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18368493887");
        message.setId("test123456");
        message.setSmsContent("【千橡科技】你的短信验证码是123456");
//        api.doSend(message);
        String a = "par=899555%2C202841%2C3036%2C18337014744%2CT%2C2018-04-04+15%3A39%3A08";
//        a = URLDecoder.decode(a,"utf-8");
        System.out.println("a="+ a);
        api.parseDeliver(a,Lists.<SMSMOMessage>newArrayList());

//        System.out.println(DigestUtils.md5Hex("testmima20120701231212"));
    }
    
}